package org.itboys.admin.web.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.itboys.admin.constant.AdminConstants;
import org.itboys.admin.constant.AdminSessionConstant;
import org.itboys.admin.dto.EasyUiTreeDO;
import org.itboys.admin.entity.AdminRole;
import org.itboys.admin.entity.BusinessCenterAdminMenu;
import org.itboys.admin.entity.BusinessCenterUser;
import org.itboys.admin.service.AdminRoleService;
import org.itboys.admin.service.BusinessCenterAdminMenuService;
import org.itboys.admin.service.BusinessCenterUserService;
import org.itboys.admin.tools.AdminCookieHolder;
import org.itboys.admin.tools.AdminPermissionCheck;
import org.itboys.admin.tools.AdminSessionHolder;
import org.itboys.admin.tools.LoginHolder;
import org.itboys.admin.tools.WebConstants;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.commons.utils.collection.CommonCollectionUtils;
import org.itboys.commons.utils.encryption.Digests;
import org.itboys.commons.utils.io.FileUtils;
import org.itboys.commons.utils.servlet.ServletContextHolder;
import org.itboys.framework.query.JsonPageUtils;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mongodb.utils.page.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.web.servlet.ModelAndView;

@RestController
@RequestMapping("/center/user")
public class CenterUserController extends BaseController {

	@Autowired
	private BusinessCenterUserService businessCenterUserService;
	@Autowired
	private ResourceHolder resourceHolder;
    @Resource
    private AdminRoleService adminRoleService;
    @Resource
    private BusinessCenterAdminMenuService businessCenterAdminMenuService;

	@ResponseBody
	@RequestMapping("/{id}")
	public BusinessCenterUser detail(@PathVariable("id") Long id) {
		return businessCenterUserService.getById(id);
	}

	/**
	 * 分页查询管理用户
	 * 
	 * @return
	 */
	@RequestMapping("/list")
	@AdminPermissionCheck("adminUser:list")
	public void list(HttpServletRequest request, HttpServletResponse response) {
        Page<BusinessCenterUser> page = businessCenterUserService.pageQuery(request);
		JsonPageUtils.renderJsonPage(page.getTotal(),page.getTotalPages(), page.getData(), response);
	}

    /**
     * 总平台：跳转到商家账号页面
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/toListVM")
    public ModelAndView toListVM(Long centerId, Model model,
                                 HttpServletRequest request, HttpServletResponse response) {
        if (centerId == null) {
            centerId = (Long) ServletContextHolder.getSession().getAttribute(AdminSessionConstant.CENTER_ID);
        }
        model.addAttribute("centerId", centerId);
        return new ModelAndView("/center/user-list");
    }


    /**
	 * 异步获取单个用户对象
	 * 
	 * @param id
	 * @param response
	 */
	@RequestMapping("/getUser/{id}")
	@AdminPermissionCheck("adminUser:getUser")
	public void getUser(@PathVariable("id") Long id,
			HttpServletResponse response) {
		BusinessCenterUser user = businessCenterUserService.getById(id);
		AjaxUtils.renderJson(response, user);
	}

	@RequestMapping("/isExists")
	public void isExists(String userName, HttpServletResponse response) {
		AjaxUtils.renderText(response,
				String.valueOf(businessCenterUserService.isExists(userName)));
	}

	/**
	 * 修改密码
	 * 
	 * @param response
	 */
	@RequestMapping("/modifyPass")
	@AdminPermissionCheck("adminUser:save")
	public void save(HttpServletRequest request, HttpServletResponse response) {
		Long id = Long.valueOf(request.getParameter("id"));
		String newPassword = request.getParameter("new_password");
		if (StringUtils.isNotEmpty(newPassword)) {

		} else {
			newPassword = "123456";
		}
		try {
			if (id != null) {
				businessCenterUserService.modifyPass(id, newPassword);
			}
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		} catch (Exception e) {
			logger.error("modify password error", e);
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}

	/**
	 * 异步保存
	 */
	@RequestMapping("/save")
	@AdminPermissionCheck("adminUser:save")
	public void save(@ModelAttribute BusinessCenterUser user,
			HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value="logos",required=false) MultipartFile logos) {
		try {
			if (logos != null && !logos.isEmpty()) {
				String filePath = FileUtils.saveFile(logos.getInputStream(),
						resourceHolder.getStringValue("fileUploadPath"),
						logos.getOriginalFilename(), logos.getContentType());
				user.setBigLogo(filePath);
			}
            if (user.getType() == BusinessCenterUser.TYPE_SUPER &&
                    businessCenterUserService.existUser(user.getCenterId())) {
                AjaxUtils.renderText(response, CommonConstants.EXISTED);
                return;
            }
            BusinessCenterUser proUser = businessCenterUserService.getAdminUser(AdminCookieHolder.getAdminUserName());
            if (proUser != null && proUser.getType() != BusinessCenterUser.TYPE_SUPER) {
                AjaxUtils.renderText(response, CommonConstants.FAIL);
                return;
            }
			if (user.getId() == 0l) {
                BusinessCenterUser newUser = businessCenterUserService.getAdminUser(user.getUsername());
                if (newUser != null) {
                    AjaxUtils.renderText(response, CommonConstants.FAIL);
                    return;
                }
                //user.setCenterId(proUser.getCenterId());
                //user.setType(BusinessCenterUser.TYPE_COMMON);
				businessCenterUserService.insert(user);
			} else {
				businessCenterUserService.doUpdate(user);
			}
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		} catch (Exception e) {
			logger.error("save admin user error", e);
			e.printStackTrace();
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}

    @RequestMapping("getUserRole/{id}")
    @AdminPermissionCheck("adminUser:getUserRole")
    public void getUserRole(@PathVariable Long id, HttpServletResponse response) {
        Map<String, Object> param = Maps.newHashMap();
        param.put("centerId", businessCenterUserService.getUserCenterId(AdminCookieHolder.getAdminUserName()));
        param.put("isDeleted", 0);
        List<AdminRole> roleList = adminRoleService.list(param);
        List<EasyUiTreeDO> tree = Lists.newArrayListWithCapacity(roleList
                .size());
        List<Long> userRole = adminRoleService.getAdminRoleByUserIds(id);
        for (AdminRole roles : roleList) {
            EasyUiTreeDO roleTree = new EasyUiTreeDO();
            roleTree.setId(roles.getId());
            roleTree.setText(roles.getName());
            if (userRole.contains(roles.getId())) {
                roleTree.setChecked(true);
            }
            tree.add(roleTree);
        }
        AjaxUtils.renderJson(response, tree);
    }

    @RequestMapping("setUserRoles")
    @AdminPermissionCheck("adminUser:setUserRoles")
    public void setUserRoles(HttpServletRequest request,
                             HttpServletResponse response) {
        try {
            Long userId = Long.valueOf(request.getParameter("userId"));
            String str = request.getParameter("roleIds");
            List<Long> roleIds = CommonCollectionUtils.splictToLongList(str,
                    ",");
            adminRoleService.insertUserRole(userId, roleIds, AdminConstants.AdminRoleType.TYPE_CENTER);
            AjaxUtils.renderText(response, CommonConstants.SUCCESS);
        } catch (Exception e) {
            AjaxUtils.renderText(response, CommonConstants.FAIL);
        }
    }

	/**
	 * 异步删除
	 */
	@RequestMapping("/delete/{id}")
	@AdminPermissionCheck("adminUser:delete")
	public void delete(@PathVariable("id") Long id, HttpServletResponse response) {
		AjaxUtils.renderText(
				response,
				String.valueOf(businessCenterUserService.deleteBy(businessCenterUserService
						.getById(id).getUsername(), id)));
	}

    /**
     * 修改商家账号状态
     * @param sellerUserId
     * @param state
     * @param response
     */
    @RequestMapping("/updateSellerUserState")
    public void updateSellerUserState(Long sellerUserId, int state, HttpServletResponse response){
        boolean result = businessCenterUserService.updateState(sellerUserId, state);
        if(result){
            AjaxUtils.renderText(response, CommonConstants.SUCCESS);
        }else{
            AjaxUtils.renderText(response, CommonConstants.FAIL);
        }
    }

	@RequestMapping("/changepassword")
	public void changePassword(HttpServletRequest request,
			HttpServletResponse response) {
		String oldpass = request.getParameter("oldpass");
		String newpass = request.getParameter("newpass");
		String upass = request.getParameter("upass");
		int i = businessCenterUserService.updatePassword(oldpass, newpass, upass);
		AjaxUtils.renderText(response, String.valueOf(i));
	}

	@RequestMapping("/getUpdateUser")
	@AdminPermissionCheck("adminUser:getUpdateUser")
	public void getUpdateUser(HttpServletResponse response) {
		AjaxUtils.renderJson(
				response,
				businessCenterUserService.getById(LoginHolder.getLoginUser(
                        WebConstants.SessionKey.ADMIN_USER).getUserid()));
	}

	@RequestMapping("/getUpdateUserInfo")
	public void getUpdateUserInfo(HttpServletResponse response) {
		AjaxUtils.renderJson(
				response,
				businessCenterUserService.getById(LoginHolder.getLoginUser(
                        WebConstants.SessionKey.ADMIN_USER).getUserid()));
	}

	@RequestMapping("/getUserLoadPass")
	public void getUser(HttpServletResponse response) {
		BusinessCenterUser user = businessCenterUserService.getById(AdminSessionHolder
                .getAdminUserId());
		AjaxUtils.renderJson(response, user);
	}
	
	@RequestMapping("/simpleUpdate")
	public void simpleSave(@ModelAttribute BusinessCenterUser adminUser,HttpServletResponse response,@RequestParam("logos") MultipartFile logos){
		try {
			if (logos != null && !logos.isEmpty()) {
				String filePath = FileUtils.saveFile(logos.getInputStream(),
						resourceHolder.getStringValue("fileUploadPath"),
						logos.getOriginalFilename(), logos.getContentType());
				adminUser.setBigLogo(filePath);
			}
			if(adminUser.getId()==0l){
				adminUser.setPassword(Digests.md5(adminUser.getPassword()));
                adminUser.setType(BusinessCenterUser.TYPE_COMMON);
				businessCenterUserService.save(adminUser);
			}else {
                BusinessCenterUser user = businessCenterUserService.getById(adminUser.getId());
				adminUser.setCr(user.getCr());
				adminUser.setCt(user.getCt());
				adminUser.setPassword(user.getPassword());
				adminUser.setUr(AdminSessionHolder.getAdminUserId());
				adminUser.setUt(System.currentTimeMillis());
				businessCenterUserService.update(adminUser);
			}
			
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		} catch (Exception e) {
			logger.error("simpleSave admin user error", e);
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}

	/**
	 * 获取所有的用户信息（带分页）
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/findAllUserAndPage")
	public Page<BusinessCenterUser> findAllUserAndPage(HttpServletRequest request) {
        long centerId = businessCenterUserService.getUserCenterId(AdminCookieHolder.getAdminUserName());
        return businessCenterUserService.findAllUserAndPage(request, centerId);
	}

    @RequestMapping("getMenuPermission/{id}")
    @AdminPermissionCheck("adminRole:getMenuPermission")
    public void getMenuPermission(@PathVariable("id") Long id,HttpServletResponse response){
        Map<String, Object> param = Maps.newHashMapWithExpectedSize(0);
        List<BusinessCenterAdminMenu> menuList = businessCenterAdminMenuService.list(param);
        List<Long> menuIds = businessCenterAdminMenuService.getAdminMenuByRoleIds(id);
        List<BusinessCenterAdminMenu> roots = businessCenterAdminMenuService.getRootsMenusIgnorePermission(menuList);
        List<EasyUiTreeDO> tree = Lists.newArrayListWithCapacity(roots.size());
        for(BusinessCenterAdminMenu menu:roots){
            EasyUiTreeDO menuTree = new EasyUiTreeDO();
            menuTree.setId(menu.getId());
            menuTree.setText(menu.getMenuName());
            if(menuIds.contains(menu.getId())){
                menuTree.setChecked(true);
            }
            tree.add(menuTree);
        }
        for(EasyUiTreeDO uitree:tree){
            for(BusinessCenterAdminMenu menu:menuList){
                if(menu.getParentId().equals(uitree.getId())){
                    EasyUiTreeDO menuTree = new EasyUiTreeDO();
                    menuTree.setId(menu.getId());
                    menuTree.setText(menu.getMenuName());
                    if(menuIds.contains(menu.getId())){
                        menuTree.setChecked(true);
                    }
                    uitree.getChildren().add(menuTree);
                }
            }
        }
        AjaxUtils.renderJson(response, tree);
    }

    @RequestMapping("/relPermissionAndMenu")
    @AdminPermissionCheck("adminRole:relPermissionAndMenu")
    public void relPermissionAndMenu(HttpServletResponse response,HttpServletRequest request){
        try {
            String str = request.getParameter("permissionIds");
            Long roleId = Long.valueOf(request.getParameter("roleId"));
            String types = request.getParameter("types");
            List<Long> permissionIds = CommonCollectionUtils.splictToLongList(str, ",");
            if(!permissionIds.isEmpty()){
                Map<Long, Long> idsTemp = Maps.newHashMapWithExpectedSize(permissionIds.size());
                permissionIds.forEach(pi -> {
                    BusinessCenterAdminMenu am = businessCenterAdminMenuService.getById(pi);
                    idsTemp.putIfAbsent(am.getParentId(), am.getParentId());
                });

                idsTemp.forEach((k,v) -> {
                    permissionIds.add(v);
                });

            }
            if(types.equals("menu")){
                adminRoleService.insertRoleMenu(roleId, permissionIds,types);
            }else{
                adminRoleService.insertRolePermission(roleId, permissionIds,types);
            }
            AjaxUtils.renderText(response, CommonConstants.SUCCESS);
        } catch (Exception e) {
            logger.error("relPermissionAndMenu error", e);
            AjaxUtils.renderText(response, CommonConstants.FAIL);
        }
    }
}
